package com.cwj;

import java.io.*;

/**
 * @author chenwujie
 * @date 2020/10/1415:18
 */
public class FileEncrypt {
    private static int mask = 0b1011_0110;
    public static void main(String[] args) throws IOException {
        String srcPath = "C:\\VScodeProjects\\pythonPros\\fileEnpyro\\山水.jpg";
        String encryptPath = "C:\\VScodeProjects\\pythonPros\\fileEnpyro\\山水副本.jpg";
        String decryptPath = "C:\\VScodeProjects\\pythonPros\\fileEnpyro\\山水副本2.jpg";
//        encryptOrDecrypt(srcPath, encryptPath);
        encryptOrDecrypt(encryptPath, decryptPath);

    }

    /**
     * 文件加/解密
     * 对源文件数据用掩码进行异或运算（对源文件进行两次运算可以得到源文件相同信息）；
     * @param src   源文件路径
     * @param path_new 新文件路径
     * @throws IOException
     */
    public static void encryptOrDecrypt(String src, String path_new) throws IOException {
        File file = new File(src);
        File file2 = new File(path_new);
        FileInputStream inputStream = new FileInputStream(file);
        FileOutputStream outputStream = new FileOutputStream(file2);

        int data = 0;
        while((data = inputStream.read()) > -1){
            outputStream.write(data ^ mask);
        }

        inputStream.close();
        outputStream.flush();
        outputStream.close();
    }

    /**
     * 对字节数组加/解密
     * @param src 源文件字节数组
     * @return 返回新的数组
     */
    public static byte[] encryptOrDecrypt(byte[] src){
        if(src == null){
            return null;
        }
        byte[] data = new byte[src.length];
        for(int i = 0; i < src.length; i++){
            data[i] = (byte)(src[i] ^ mask);
        }
        return data;
    }
}
